// 根据具体接口修改 "getMessageList"
import { getExamine as getTableData } from 'Services/hu.js';
import { get } from 'lodash';

const NAME_SPACE = 'busManageExamine'; // 此处需修改namespace名称

// 根据情况求改format函数
function formatTableDataSource(result, pageNo, pageSize) {
  /* format data */
  return result.map((item, index) => ({
    index: index + 1 + (pageNo - 1) * pageSize,
    ...item,
  }));
}

export default {
  namespace: NAME_SPACE,
  state: {
    tableDataSource: [],
    pageNo: 1,
    pageSize: 10,
    total: 0,
    filterParams: {},
    detailData: {},
  },
  effects: {
    // 获取表格数据
    *fetchTableDataSource(payload, { call, put, select }) {
      const params = yield select(({ [NAME_SPACE]: { pageNo, pageSize, filterParams } }) => ({
        pageNo,
        pageSize,
        ...filterParams,
      }));

      const res = yield call(getTableData, params);

      yield put({
        type: 'SET_TOTAL',
        payload: get(res, 'total', 0),
      });

      yield put({
        type: 'SET_TABLE_DATA_SOURCE',
        payload: get(res, 'data', []),
      });
    },

    // 更新pageNo、 pageSize， 并重新请求表格数据
    *updatePagination({ payload }, { put }) {
      yield put({ type: 'SET_PAGINATION', payload });
      yield put({ type: 'fetchTableDataSource' });
    },

    // 更新筛选数据， 并重新请求表格数据
    *updateFilterParams({ payload }, { put }) {
      yield put({ type: 'SET_FILTER_PARAMS', payload });
      yield put({ type: 'fetchTableDataSource' });
    },
  },
  reducers: {
    SET_TABLE_DATA_SOURCE(state, { payload: tableDataSource }) {
      return {
        ...state,
        tableDataSource: formatTableDataSource(tableDataSource, state.pageNo, state.pageSize),
      };
    },

    SET_TOTAL(state, { payload: total }) {
      return {
        ...state,
        total,
      };
    },

    SET_PAGINATION(
      state,
      {
        payload: { pageNo, pageSize },
      }
    ) {
      return {
        ...state,
        pageNo,
        pageSize,
      };
    },

    SET_FILTER_PARAMS(state, { payload: filterParams }) {
      return {
        ...state,
        filterParams,
      };
    },

    SET_DETAIL_DATA(state, { payload }) {
      return {
        ...state,
        detailData: {
          num: state.filterParams.num,
          ...payload,
        },
      };
    },
  },
};
